﻿<%@ WebHandler Language="C#" Class="ajaxcustomer" %>

using System;
using System.Web;
using System.Web.SessionState;
using GZ.Entity;
using GZ.Common;
using Newtonsoft.Json;
using System.Data;
/// <summary>
/// 客户ajax处理方法
/// </summary>
public class ajaxcustomer : IHttpHandler, IRequiresSessionState
{
    HttpRequest Request;
    HttpResponse Response;
    HttpSessionState Session;
    HttpServerUtility Server;
    HttpCookieCollection Cookie;
    ECustomer customerAccessor = new ECustomer();
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            Request = context.Request;
            Response = context.Response;
            Session = context.Session;
            Server = context.Server;
            Cookie = context.Request.Cookies;
            string method = Request["methodName"].ToString();
            System.Reflection.MethodInfo methodInfo = this.GetType().GetMethod(method);
            methodInfo.Invoke(this, null);
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }

    /// <summary>
    //查询库中邮箱(保证注册邮箱唯一性)，如果有则不让注册，返回false
    /// </summary>
    public void CustomerIsEffective()
    {
        String email = Request["txt_Email"].TrimEnd(new char[] { ',' });
        Response.Write(customerAccessor.IsExistCustomerByEmail(email) == false ? "此邮箱可以注册!" : "此邮箱已存在,请先登录!");
    }
    /// <summary>
    /// 添加注册用户
    /// </summary>
    public void CustomerReg()
    {
        #region 添加注册用户
        ECustomer _ECustomer = new ECustomer();
        _ECustomer.CustomerName = Request["txt_CustomerName"];
        _ECustomer.Email = Request["txt_Email"];
        _ECustomer.Pwd = SecurityEncryption.MD5(Request["txt_PWD"].ToString(), 16);
        _ECustomer.TelNum = Request["txt_TelNum"].ToString();
        _ECustomer.RegionId = Convert.ToInt32(Request["sel_RegionId"]);
        _ECustomer.BusinessDistrictId = Convert.ToInt32(Request["sel_BusinessDistrictId"]);
        _ECustomer.OfficeId = Convert.ToInt32(Request["sel_OfficeId"]);
        _ECustomer.FloorId = Convert.ToInt32(Request["sel_FloorId"]);
        _ECustomer.Address = Request["txt_Address"];
        _ECustomer.Memo = String.Empty;
        _ECustomer.IsDelete = 0;
        int reffectRows = customerAccessor.Insert(_ECustomer);
        CookieUserObject userObj = new CookieUserObject(reffectRows.ToString(), Request["txt_CustomerName"], Request["txt_Email"]);
        userObj.RegionId = Request.QueryString["sel_RegionId"];
        userObj.BusinessDistrictId = Request.QueryString["sel_BusinessDistrictId"];
        userObj.OfficeId = Request.QueryString["sel_OfficeId"];
        userObj.FloorId = Request.QueryString["sel_FloorId"];

        Register(userObj);
        Response.Write("gz_注册成功!");
        #endregion
    }
    /// <summary>
    /// 用户登录
    /// </summary>
    public void CustomerLogin()
    {
        #region 用户登录

        String userEmail = Request.Form["txtEmail"];
        String userPwd = SecurityEncryption.MD5(Request.Form["txtPwd"].ToString(), 16);

        System.Data.DataTable user = customerAccessor.GetCustomerByEmailPwd(userEmail, userPwd);
        if (user != null && user.Rows.Count != 0)
        {
            CookieUserObject userObj = new CookieUserObject(user.Rows[0]["id"].ToString(), HttpUtility.UrlEncode(user.Rows[0]["CustomerName"].ToString()), userEmail);
            userObj.RegionId = user.Rows[0]["RegionId"].ToString();
            userObj.BusinessDistrictId = user.Rows[0]["BusinessDistrictId"].ToString();
            userObj.OfficeId = user.Rows[0]["OfficeId"].ToString();
            userObj.FloorId = user.Rows[0]["FloorId"].ToString();

            Register(userObj);
            Response.Write("登录成功!");
        }
        else
        {
            Response.Write("用户名或者密码输入不正确");
        }

        #endregion
    }

    /// <summary>
    /// 设置用户Cookie
    /// </summary>
    /// <param name="user"></param>
    private void Register(CookieUserObject user)
    {
        HttpCookie cookie = new HttpCookie("gz_customer");
        user.Name = HttpUtility.UrlEncode(user.Name);
        cookie.Value = JsonConvert.SerializeObject(user);
        cookie.Expires = DateTime.MaxValue;
        Response.Cookies.Add(cookie);
    }
    /// <summary>
    /// 获取配送时段
    /// </summary>
    public void LoadDeliveryarea()
    {
        EDeliveryArea deliveryAreaAccessor = new EDeliveryArea();
        int id = 0;
        if (!String.IsNullOrEmpty(Request.QueryString["id"]))
        {
            if (!int.TryParse(Request.QueryString["id"], out id))
            {
                Response.Write("{}");
            }
            else
            {
                id = Convert.ToInt32(Request.QueryString["id"]);
            }
        }

        DataTable dtAreas = deliveryAreaAccessor.GetDeliveryArea(id);
        if (dtAreas != null && dtAreas.Rows.Count != 0)
        {
            Response.Write(JsonConvert.SerializeObject(dtAreas));
        }
    }


    /// <summary>
    /// 获取指定楼层信息
    /// </summary>
    public void QueryFloorDefaultValue()
    {
        EDeliveryArea deliveryAreaAccessor = new EDeliveryArea();
        int id = 0;
        if (!String.IsNullOrEmpty(Request.QueryString["id"]))
        {
            if (!int.TryParse(Request.QueryString["id"], out id))
            {
                Response.Write("");
            }
            else
            {
                id = Convert.ToInt32(Request.QueryString["id"]);
            }
        }

        DataTable dtAreas = deliveryAreaAccessor.GetDeliveryAreaByIds(id.ToString());

        if (dtAreas != null && dtAreas.Rows.Count != 0)
        {
            Response.Write(dtAreas.Rows[0]["DefaultCompanyName"]);
        }
    }

    /// <summary>
    /// 获取配送时段
    /// </summary>
    public void LoadDeliveryDate()
    {
        EDeliveryPeriod deliveryPeriodAccessor = new EDeliveryPeriod();
        System.Data.DataTable dtperiods = deliveryPeriodAccessor.GetDeliveryPeriod();
        if (dtperiods != null && dtperiods.Rows.Count != 0)
        {
            Response.Write(JsonConvert.SerializeObject(dtperiods));
        }
        else
        {
            Response.Write("{}");
        }
    }
    /// <summary>
    ///前台加载客户搜索历史订单
    /// </summary>
    public void LoadCustomerOrders()
    {
        EOrder orderAccessor = new EOrder();
        if (Request.Cookies["gz_customer"] != null)
        {
            CookieUserObject user = JsonConvert.DeserializeObject<CookieUserObject>(Request.Cookies["gz_customer"].Value);
            DataTable dtCustomerOrders = null;
            if (!String.IsNullOrEmpty(Request.QueryString["start"]) && !String.IsNullOrEmpty(Request.QueryString["end"]))
            {
                dtCustomerOrders = orderAccessor.GetOrdersByCreateDate(Convert.ToDateTime(Request.QueryString["start"]), Convert.ToDateTime(Request.QueryString["end"]), Convert.ToInt32(user.Id));
            }
            else
            {
                dtCustomerOrders = orderAccessor.GetOrdersByCreateDate(DateTime.Now.AddDays(-30), DateTime.Now, Convert.ToInt32(user.Id));

            }
            if (dtCustomerOrders != null && dtCustomerOrders.Rows.Count != 0)
            {
                Response.Write(JsonConvert.SerializeObject(dtCustomerOrders));
            }
            else
            {
                Response.Write("{}");
            }
        }
        else
        {
            Response.Write("{}");
        }
    }
    /// <summary>
    ///  提交订单（主要用于客户取消的订单恢复提交）
    /// </summary>
    public void SubmitOrCancelCustomerOrder()
    {
        String oid = Request.QueryString["oid"];
        String ste = Request.QueryString["ste"];
        bool state = false;
        if (ste == "2")//如果是审核订单，直接停止操作。不予任何。
        {
            state = false;
        }
        else
        {
            if (!String.IsNullOrEmpty(oid) && !String.IsNullOrEmpty(ste))
            {
                int _oid = 0;
                int _ste = 0;

                if (int.TryParse(oid, out _oid) && int.TryParse(ste, out _ste))
                {
                    EOrder orderAccessor = new EOrder();
                    if (_ste == 1)
                    {
                        state = orderAccessor.CancelOrder(_oid);

                    }
                    else
                    {
                        state = orderAccessor.SubmitOrder(_oid);
                    }
                }
            }
        }

        Response.Write(state ? "1" : "0");
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}
